package com.bcbim.common.util;

import com.google.common.collect.Lists;
import org.apache.commons.beanutils.BeanUtils;

import java.util.*;

/**
 * @Description: 集合工具类
 * @Author haoshuai
 * @Date 2021/7/6
 * @Version V1.0
 **/
public class MyListUtil {

    /**
     * @Description: list copy
     * @Param: sourceList 源list
     * @Param: beanClass copy list 的 class
     * @Return: List<T>
     * @Author: haoshuai
     * @Date: 2021/7/6
     */
    public static <T> List<T> copy(Object sourceList, Class<?> beanClass) throws Exception {
        List<Object> sList = (List<Object>) sourceList;
        List<Object> tList = Lists.newArrayList();
        for (Object s : sList) {
            Object o = beanClass.newInstance();
            BeanUtils.copyProperties(s, o);
            tList.add(o);
        }
        return (List<T>) tList;
    }

    /**
     * @Description: 重写 list.removeAll 方法, 提高效率
     * @Param: source
     * @Param: destination
     * @Return: List<T>
     * @Author: haoshuai
     * @Date: 2021/8/24
     */
    public static <T> List<T> removeAll(List<T> source, List<T> destination) {
        List<T> result = new LinkedList<>();

        Map<T, Integer> sourceMap = new HashMap<>();
        for (T t : source) {
            if (sourceMap.containsKey(t)) {
                sourceMap.put(t, sourceMap.get(t) + 1);
            } else {
                sourceMap.put(t, 1);
            }
        }

        Set<T> all = new HashSet<T>(destination);
        for (Map.Entry<T, Integer> entry : sourceMap.entrySet()) {
            T key = entry.getKey();
            Integer value = entry.getValue();
             if (all.add(key)) {
                for (int i = 0; i < value; i++) {
                    result.add(key);
                }
            }
        }
        return result;
    }

}
